<template>
  <div class="main new-buyer-goods-list">
    <section>
      <div class="header-container">
        <el-button v-if="rightsButtons['goodsAdd']" type="primary" size="mini" @click="chooseGoods">添加商品</el-button>
        <el-button v-if="rightsButtons['packagesAdd']" type="primary" size="mini" plain @click="chooseGoodsPackage">添加套餐</el-button>
      </div>
      <search-form :listQuery="listQuery" :queryConfig="queryConfig" :labelWidth="100" :search="search" />
      <el-table :data="list.filter(item => (item.deleteFlag===1))" v-loading="listLoading" header-row-class-name="table-header" element-loading-text="给我一点时间" border highlight-current-row>
        <el-table-column align="center" label="ID" prop="productId" min-width="100"></el-table-column>
        <!--<el-table-column align="center" label="主图" prop="productImage" min-width="100" show-overflow-tooltip>
                    <template slot-scope="scope">
                        <img :src="scope.row.productImage" style="max-width: 60px;max-height: 60px;"/>
                    </template>
                </el-table-column>-->
        <el-table-column align="center" label="名称" prop="productName" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{scope.row.productName || '-'}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="类型" prop="productType" min-width="100">
          <template slot-scope="scope">
            {{scope.row.productType===1? '商品' : '套餐'}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="可购买用户标签" prop="productType" min-width="100">
          <template slot-scope="scope">
            {{scope.row.name}}
            <i v-if="rightsButtons['label']" class="el-icon-edit" @click="showEdit(scope.row)"></i>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="150" v-if="rightsButtons['delete']">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" plain @click="scope.row.deleteFlag=0">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="footer-container">
        <el-button type="success" size="mini" :loading="btnLoading" plain @click="save">保 存</el-button>
      </div>
    </section>
    <el-dialog title="可购买用户标签" :visible.sync="dialogVisible" width="30%">
      <span>用户标签：</span>
      <el-select v-model="currentTags" placeholder="请选择">
        <el-option v-for="item in userTag" :key="item.id" :label="item.name" :value="item.id">
        </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveTags">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import differenceBy from 'lodash/differenceBy'
import searchForm from '../../../components/searchForm/index'
import { goodsCheck } from '@/api/activity/fullReduce'

export default {
  name: 'newBuyer',
  components: {
    searchForm
  },
  data() {
    return {
      idList: [],
      currentTags: [], //当前选择标签集合
      currentData: {},
      dialogVisible: false,
      listLoading: false,
      listQuery: {
        pageIndex: 1,
        pageSize: 1000,
        goodsId: '',
        goodsTitle: '',
        isPage: 0
      },
      queryConfig: [
        {
          prop: 'goodsId',
          type: 'input',
          label: '商品ID'
        },
        {
          prop: 'goodsTitle',
          type: 'input',
          label: '商品标题'
        }
      ],
      list: [],
      btnLoading: false,
      userTag: [],
      tempGoodsCheck: [],
      tempPackageChecked: []
    }
  },
  created() {
    this.getUserTag()
  },
  methods: {
    getList() {
      this.listLoading = true
      this.request({
        url: '/bsnl-activity/newUserProduct/goods/list',
        method: 'get',
        params: this.listQuery
      })
        .then(({ data }) => {
          this.list = data
          this.tempGoodsCheck = []
          this.tempPackageChecked = []
          this.list.map(item => {
            if (item.productType === 1) {
              this.tempGoodsCheck.push({
                id: item.productId,
                name: item.productName
              })
            } else if (item.productType === 2) {
              this.tempPackageChecked.push({
                packageId: item.productId,
                name: item.productName
              })
            }
          })
          this.getUserTagsType()
          // this.listTotal = totalCount;
          this.listLoading = false
        })
        .catch(err => {
          console.log(err)
          this.list = []
          // this.listTotal = 0;
          this.listLoading = false
        })
    },
    getUserTagsType() {
      this.list.map(item => {
        const ids = item.tags // 用户标签类型有多种
        item.name = []
        for (let tag of this.userTag) {
          if (tag.id === Number(ids)) {
            item.name.push(tag.name)
          }
        }
        item.name = item.name.join(',')
      })
    },
    // 获取用户标签
    async getUserTag() {
      try {
        const { data } = await this.request({
          url: '/bsnl-activity/newUserProduct/tags',
          method: 'get'
        })
        this.userTag = data
        this.getList()
      } catch (error) {
        console.log(error)
      }
    },
    // 搜索
    search() {
      this.listQuery.pageIndex = 1
      this.getList()
    },
    saveTags() {
      const idx = this.list.findIndex(it => it.productId === this.currentData.productId)
      console.log('@@@', this.currentTags)
      this.list[idx].tags = this.currentTags
      //   if (idx !== -1) {
      //     if (this.currentTags.length === 0) {
      //       this.list[idx].tags = ''
      //     } else {
      //       this.list[idx].tags = this.currentTags.join(',')
      //     }
      //   }
      this.getUserTagsType()
      this.dialogVisible = false
    },
    showEdit(val) {
      this.currentData = val
      this.dialogVisible = true
      if (val.tags) {
        console.log('1', val.tags)
        this.currentTags = Number(val.tags)
      } else {
        console.log('2', val.tags)
        this.currentTags = ''
      }
      console.log('cccc', this.currentTags)
    },
    async checkActivity(val, idList, type) {
      const goodsType = type === 'single' ? 'id' : 'packageId'
      let newArr = []
      const arr = val.map(async(item, index) => {
        if (!idList.includes(item[goodsType])) {
          const param = {
            id: item[goodsType],
            checkList: [1, 2, 3, 4] // 互斥类型
          }
          const res = await goodsCheck(param)
          if (res.status === 200) {
            newArr.push(item)
            return item
          }
        } else {
          newArr.push(item)
          return item
        }
      })
      let result = await Promise.all(arr)
      return result
    },
    // 选择商品
    async chooseGoods() {
      let idList = []
      let newArr = []
      this.tempGoodsCheck.map(item => {
        idList.push(item.id)
      })
      this.checkGoods(this.tempGoodsCheck, -1, true, null, true)
        .then(async val => {
          // 检验活动重复
          newArr = await this.checkActivity(val, idList, 'single')
          newArr = newArr.filter(item => {
            return item !== undefined
          })
          // 校验end
          val = newArr
          this.tempGoodsCheck = val
          let goodsList = this.list.filter(item => item.productType === 1)
          let selectVal = []
          val.map(item => {
            selectVal.push({
              productId: item.id,
              productName: item.name
            })
          })
          let needDelGoods = differenceBy(goodsList, selectVal, 'productId')
          let needAddGoods = differenceBy(selectVal, goodsList, 'productId')

          needDelGoods.map(item => {
            let index = this.list.findIndex(subItem => subItem.productId === item.productId)
            if (index >= 0) {
              this.list[index].deleteFlag = 0
            }
          })

          needAddGoods.map(async item => {
            this.list.push({
              productType: 1,
              productId: item.productId,
              productName: item.productName,
              deleteFlag: 1
            })
          })
        })
        .catch(err => {
          this.tempGoodsCheck = []
        })
    },
    // 选择套餐
    async chooseGoodsPackage() {
      let idList = []
      let newArr = []
      this.tempPackageChecked.map(item => {
        idList.push(item.packageId)
      })
      this.checkPackage(this.tempPackageChecked)
        .then(async val => {
          // 检验活动重复
          newArr = await this.checkActivity(val, idList, 'package')
          newArr = newArr.filter(item => {
            return item !== undefined
          })
          // 校验end
          val = newArr
          this.tempPackageChecked = val
          let packageList = this.list.filter(item => item.productType === 2)
          let selectVal = []
          val.map(item => {
            selectVal.push({
              productId: item.packageId,
              productName: item.name
            })
          })
          let needDelPackage = differenceBy(packageList, selectVal, 'productId')
          let needAddPackage = differenceBy(selectVal, packageList, 'productId')

          needDelPackage.map(item => {
            let index = this.list.findIndex(subItem => subItem.productId === item.productId)
            if (index >= 0) {
              this.list[index].deleteFlag = 0
            }
          })
          needAddPackage.map(item => {
            console.log(item, this.list)
            this.list.push({
              productType: 2,
              productId: item.productId,
              productName: item.productName,
              deleteFlag: 1
            })
          })
        })
        .catch(err => {
          this.tempPackageChecked = []
        })
    },
    save() {
      this.btnLoading = true
      this.request({
        url: '/bsnl-activity/newUserProduct/save',
        method: 'post',
        data: this.list
      })
        .then(() => {
          this.$message.success('保存成功')
          this.getList()
          this.btnLoading = false
        })
        .catch(err => {
          this.btnLoading = false
        })
    }
  }
}
</script>
<style lang="scss">
.new-buyer-goods-list {
  .header-container {
    padding-bottom: 24px;
  }
  .footer-container {
    padding-top: 24px;
    text-align: center;
  }
}
</style>
